#!/bin/sh
# shellcheck shell=dash disable=SC2169,SC1091
#
# Startup script for ha-proxy which proxies HTTP
# requests from the HomeAssistant UI to the HomeMatic WebUI
#

# source all data from /var/hm_mode
[[ -r /var/hm_mode ]] && . /var/hm_mode

# only continue if HAPROXY is defined
[[ -z "${HM_HAPROXY_SRC}" ]] && exit 0

start() {
  printf  "Starting ha-proxy: "

  export HM_HAPROXY_SRC
  export NODE_PATH=/usr/lib/node_modules
  if start-stop-daemon -S -q -m -b -p /var/run/ha-proxy.pid --exec /bin/ha-proxy.js; then
    sleep 1
    # check if ha-proxy could be started
    if start-stop-daemon -K -q -t -p /var/run/ha-proxy.pid 2>/dev/null; then
      echo "OK"
    else
      echo "FAIL"
    fi
  else
    echo "FAIL"
  fi
}

stop() {
  printf "Stopping ha-proxy: "
  if start-stop-daemon -K -q -p /var/run/ha-proxy.pid; then
    echo "OK"
  else
    echo "FAIL"
  fi
  rm -f /var/run/ha-proxy.pid
}

restart() {
  stop
  start
}

case "$1" in
  start)
    start
  ;;
  stop)
    stop
  ;;
  restart)
    restart
  ;;
  *)
    echo "Usage: ha-proxy {start|stop|restart}"
    exit 1
esac

exit 0
